const allStore = {}
const actions = {}

/**
 *  pages 文件夹下的 store 文件夹或 store.js，自动生成 redux 的 store
 */
const buildStore = (storeUrl, storeFileModule) => {
  if (!/(store\.js$)|(^.[/\\][\S\s]+[/\\]store[/\\]\w+.js$)/.test(storeUrl)) { return }
  let key
  if (/store\.js$/.test(storeUrl)) {
    key = storeUrl.replace(/^\.[/\\]([\S\s]+)[/\\]store\.js$/, (_, arg1) =>
      arg1.replace(/[/\\]/g, '_')
    )
  }
  const storeFileReg = /^.[/\\]([\S\s]+)[/\\]store[/\\](\w+).js$/ // 默认贪婪匹配
  if (storeFileReg.test(storeUrl)) {
    let lastStoreFolder
    key = storeUrl.replace(storeFileReg, (_, arg1, arg2) => {
      lastStoreFolder = `${arg1}/store/${arg2}`
      return `${arg1}/${arg2}`.replace(/[/\\]/g, '_')
    })
    if (key in allStore) {
      key = undefined
      console.warn(`${lastStoreFolder}无效,请修改文件名`)
    }
  }

  actions[key] = {}
  // 生成 actions =>包含所有的 store 文件中的 action
  const currentModule = storeFileModule?.(storeUrl) || {}
  Object.keys(currentModule).forEach((item) => {
    if (item !== 'default') {
      actions[key][item] = (...args) => {
        if (window.DISPATCH) {
          return window.DISPATCH(currentModule[item](...args))
        }
        return currentModule[item](...args)
      }
    }
  })

  allStore[key] = (
    state = storeFileModule(storeUrl)?.default || {},
    action
  ) => {
    switch (action.type) {
      case `${key}/save`:
        return Object.assign({}, state, {
          ...(action.data || action.payload || {})
        })
      default:
        return state
    }
  }
}
// 排除不需要创建路由的文件
const isExcludeFile = (url) => {
  // 排除 store.js, api.js, Layout, Login, Components
  // Windows 下 \  mac 下是 /
  const reg =
    /((\/|\\)(404|Layout|Login|(C|c)omponents|store|contants)(\/|\\))|(store\.js$)|(api\.js$)/
  return reg.test(url)
}
const apis = {}
const router = []
// 读 pages 下的 js 文件
const readPagesFile = () => {
  const requireResult = require.context('../pages', true, /\.js$/)
  requireResult.keys().forEach((item) => {
    // 提取 apis
    if (/api\.js$/.test(item)) {
      const key = item.replace(/^\.[/\\]([\S\s]+)[/\\]api\.js$/, (_, arg1) =>
        arg1.replace(/[/\\]/g, '_')
      )
      const exportApi = requireResult(item)?.default
      if (Object.prototype.toString.call(exportApi) === '[object Object]') {
        apis[key] = {
          ...exportApi
        }
      }
    }
    // 生成 allStore 和 actions
    buildStore(item, requireResult)

    if (isExcludeFile(item)) return
    const defaultComponent = requireResult(item)?.default
    let path = ''
    if (/index\.js$/.test(item)) {
      path = item.replace(
        /\.(.*)(\/|\\)index\.js/,
        (_, arg1) => arg1.replace(/\\/g, '/') || '/'
      )
    } else {
      path = item.replace(/\.(.+)\.js/, (_, arg1) => arg1.replace(/\\/g, '/'))
    }
    if (defaultComponent) {
      router.push({
        path,
        component: defaultComponent,
        componentPath: item
      })
    }
  })
  return router
}
readPagesFile()

export { apis, actions, router, allStore }
